package com.gch.controller;

import com.gch.pojo.Result;
import com.gch.pojo.Student;
import com.gch.pojo.Teacher;
import com.gch.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;

@RestController
@RequestMapping("/teacher")
public class TeacherController {
    @Autowired
    private RestTemplate restTemplate;  // 请求

    @Autowired
    private LoadBalancerClient loadBalancerClient;  // 自动获取地址
    @Autowired
    private TeacherService teacherService;

    @GetMapping("/findOne")
    public Teacher findOne(Integer id){
        return teacherService.findOneTea(id);
    }
    @PostMapping("/edit")
    public Result editTea(@RequestBody Teacher teacher){
        teacherService.editTea(teacher);
        return new Result(true,"成功!!!");
    }
    @PostMapping("/insert")
    public Result insert(@RequestBody Teacher teacher){
        teacherService.insertTea(teacher);
        return new Result(true,"成功!!!");
    }
    @DeleteMapping("/del")
    public Result del(Integer id){
        ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-student");
        Teacher teacher = teacherService.findById(id);
        teacherService.del(id);
        String sid = teacher.getSid();
        if (sid==null && sid==""){
            return new Result(true,"");
        }
        String[] split = sid.split(",");
        for (String s : split) {
            Integer of = Integer.valueOf(s);
            String url = serviceInstance.getUri()+"/student/edit?id="+of;
            restTemplate.getForObject(url,Student.class);
            System.out.println(url+"/student/edit?id="+id);
        }
        return new Result(true,"成功!!!");
    }
    @GetMapping("/findAll")
    public Teacher findAll(Integer id){
        ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-student");
        Teacher teacher=teacherService.findById(id);
        String sid = teacher.getSid();
        String[] split = sid.split(",");
        ArrayList<Student> students = new ArrayList<>();
        for (String s : split) {
            Integer of = Integer.valueOf(s);
            String url = serviceInstance.getUri()+"/student/findAll?id="+of;
            Student studentList = restTemplate.getForObject(url,Student.class);
            students.add(studentList);
        }
        teacher.setStudents(students);
        return teacher;
    }

}
